<?php
namespace app\common\libs;

class Sms
{
	var $goSend = true;					// 是否走发送通道

	function __construct() {

		$this->sms = new \alidayu\SmsDemo(config('alidayu.appid'), config('alidayu.appsecret'));
	}

	function sendVCode($phonenum) {
		$ali_data = [];
		$sendRes = ['state'=>true, 'msg'=>'发送成功'];

		$sms_model = new \app\common\model\SmsMobile;

		$info = $sms_model->getSentInfo($phonenum, 'register');

		if($info['total'] >= config('alidayu.max_num')) {
			$sendRes = ['state'=>false, 'msg'=>'达到当天发送上限'];
			goto goend;
		}

		$interval = config('alidayu.interval');

		if($info['last_time'] !== 0 && ($reduce = time()-$info['last_time']) <= $interval) {
			$sendRes = ['state'=>false, 'msg'=>($interval-$reduce).'秒后再试'];
			goto goend;
		}

		$code = $this->getCode();
		$tpl_num = $this->vcodeNum();

		if($this->goSend)
			$res = $this->sms->sendSms(config('alidayu.signName'), $tpl_num, $phonenum, ['code'=>$code]);
		else
			$res = $this->localSent();

		// SDK有更新时区，在此将时间改回北京时间
		date_default_timezone_set("PRC");
		if($res->Message !== 'OK'){
			$sendRes['state'] = false;
			$sendRes['msg'] = $res->Message;
		}

		$sms_data = [
			'mobile' => $phonenum,
			'date' => date('Y-m-d'),
			'scene' => 'register',
			'status' => $sendRes['state'],
			'expire_time' => date('Y-m-d H:i:s',time()+config('alidayu.effective')),
			'code' => $code,
			'message' => $res->Message,
			'tpl' => $tpl_num,
			'ali_request_id' => $res->RequestId,
			'ali_code' => $res->Code,
			'ali_bizid' => isset($res->BizId) ? $res->BizId : '',
			];
		$sms_model->save($sms_data);
		goend:

		return $sendRes;
	}

	public function createPayCode($mobile) {

		$sms_model = new \app\common\model\SmsMobile;
		$code = $this->getCode();
		$sms_data = [
			'mobile' => $mobile,
			'date' => date('Y-m-d'),
			'scene' => 'paycode',
			'status' => 1,
			'expire_time' => date('Y-m-d H:i:s',time()+config('alidayu.effective')),
			'code' => $code,
		];
		return $sms_model->save($sms_data) ? ['state'=>true, 'code'=>$code] : ['state'=>false, 'code'=>''];
	}

	private function getCode() {
		$code_box = [];
		for($i=0; $i<3;$i++) {
			$code_box[] = mt_rand(0,9);
		}

		array_splice($code_box, 2,0, $code_box[0]);

		return implode('', $code_box);
	}


	private function vcodeNum() {
		$tplNumStr = config('alidayu.code_templateCode');
		$tplArr = explode(',', $tplNumStr);

		$key = array_rand($tplArr);
		return $tplArr[$key];
	}

	private function localSent() {
		 $obj = new \StdClass();
		 $obj->Message = '本地发送';
		 $obj->RequestId = '0';
		 $obj->Code = '0';
		 $obj->BizId = '0';

		 return $obj;
	}
}